﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

using UploadersLib.Helpers;

namespace NotYetTweetRead
{
    public partial class LoginForm : Form
    {
        private TwitterSaveData g_TwitterData = new TwitterSaveData();
        private oAuthTwitter g_oAuthTwitter = null;
        //--------------------------------------------------------------------------
        //コンストラクタ
        //--------------------------------------------------------------------------
        public LoginForm(TwitterSaveData td, oAuthTwitter at)
        {
            InitializeComponent();
            g_oAuthTwitter = at;
            g_TwitterData = td;
            UserTextBox.Text = td.UserName;
            PassTextBox.Text = td.Password;
        }
        //--------------------------------------------------------------------------
        //--------------------------------------------------------------------------
        private void LoginForm_Load(object sender, EventArgs e)
        {
        }
        //--------------------------------------------------------------------------
        //テキストボックス書き込み変更
        //--------------------------------------------------------------------------
        private void TwitterTextBox_TextChanged(object sender, EventArgs e)
        {
            LoginButton.Enabled = (UserTextBox.Text != "" && PassTextBox.Text != "") ? true : false;
        }
        //--------------------------------------------------------------------------
        //パスワード表示
        //--------------------------------------------------------------------------
        private void PassCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            PassTextBox.PasswordChar = (PassCheckBox.Checked) ? '\0' : '●';
        }
        //--------------------------------------------------------------------------
        //ログインクリック
        //--------------------------------------------------------------------------
        LoadingForm loadingForm = new LoadingForm();
        int LoginPage = 1;
        private void LoginButton_Click(object sender, EventArgs e)
        {
            //接続中...
            loadingForm = new LoadingForm();
            loadingForm.Owner = this;
            loadingForm.Show();

            //
            LoginPage = 1;
            g_oAuthTwitter.Reset();
            string url = g_oAuthTwitter.AuthorizationLinkGet();
            webBrowser1.Navigate(new Uri(url));
            while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }
            HtmlElementCollection all = webBrowser1.Document.All;
            HtmlElementCollection userforms = all.GetElementsByName("session[username_or_email]");
            HtmlElementCollection passForms = all.GetElementsByName("session[password]");
            HtmlElement allowforms = webBrowser1.Document.GetElementById("allow");
            if (userforms.Count != 0 && passForms.Count != 0)
            {
                userforms[0].InnerText = UserTextBox.Text;
                passForms[0].InnerText = PassTextBox.Text;
                allowforms.InvokeMember("click");
            }
            else
            {
                loadingForm.Close();
                MessageBox.Show("ログインに失敗しました");
            }
        }
        //--------------------------------------------------------------------------
        //ドキュメントコンプリート
        //--------------------------------------------------------------------------
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //ログイン1P目
            if (LoginPage == 1)
            {
                LoginPage = 2;
            }
            //ログイン2P目
            else if (LoginPage == 2)
            {
                //間違っている場合は1P目に戻す
                string html = webBrowser1.Document.Body.InnerHtml;
                if (html.IndexOf("ユーザー名かパスワードが無効です") != -1)
                {
                    loadingForm.Close();
                    MessageBox.Show("ユーザー名かパスワードが無効です");
                    LoginPage = 1;
                }
                //ログイン成功のため情報取得して終了
                else
                {
                    //CODEタグの中の情報取得
                    MatchCollection mc = Regex.Matches(html, @"<CODE>(.*?)</CODE>");
                    string strPIN = "";
                    foreach (System.Text.RegularExpressions.Match m in mc)
                    {
                        strPIN = m.Groups[1].Value;
                    }
                    //情報を設定
                    TwitterAuthInfo acc = new TwitterAuthInfo();
                    acc.PIN = strPIN;
                    acc.OAuthToken = g_oAuthTwitter.AuthInfo.OAuthToken;
                    g_oAuthTwitter.AccessTokenGet(ref acc);
                    g_TwitterData.AccessToken = acc.Token;
                    g_TwitterData.AccessTokenSecret = acc.TokenSecret;
                    g_TwitterData.UserName = UserTextBox.Text;
                    g_TwitterData.Password = PassTextBox.Text;
                    //終了
                    loadingForm.Close();
                    this.DialogResult = DialogResult.OK;
                    Close();
                }
            }

        }


    }
}
